﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;

namespace ProjectEulerSolutions
{
    /*
     * Kao problem 18, samo s vise linija
     * 
     * */
    class Problem67
    {
        public static string Calculate()
        {
            WebClient wc = new WebClient();
            var input = wc.DownloadString("http://projecteuler.net/project/triangle.txt");

            var matches = Regex.Matches(input, "[0-9]+").Cast<Match>()
                .Select(xv => xv.Value).ToList();


            int x = 0;
            int y = 1;

            long[] sums = new long[matches.Count];

            sums[0] = int.Parse(matches[0]);

            for (int i = 1; i < matches.Count; i++)
            {
                if (x == 0) //-y
                {
                    sums[i] = int.Parse(matches[i]) + sums[i - y];
                }
                else if (x == y) //-y-1
                {
                    sums[i] = int.Parse(matches[i]) + sums[i - y - 1];
                }
                else //oboje
                {
                    //vecu ili svejedno
                    sums[i] = int.Parse(matches[i]) + (sums[i - y - 1] > sums[i - y] ? sums[i - y - 1] : sums[i - y]);
                }

                x++;
                if (x > y)
                {
                    y++;
                    x = 0;
                }
            }

            long max = 0;
            for (int i = sums.Length - 1 - y - 1; i < sums.Length; i++)
            {
                if (sums[i] > max)
                    max = sums[i];
            }

            return max.ToString();
        }
    }
}
